#!/bin/bash
# Check the common.sh script
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
COMMON_SHELL="$SCRIPT_DIR/../common.sh" 
SFTP_TOOL="$SCRIPT_DIR/../tools/sftp"

if [ ! -f "$COMMON_SHELL" ]; then
    if [ ! -f ./common.sh ]; then
        wget https://gitee.com/anolis/hygon-devkit/raw/master/common.sh
        chmod +x common.sh
    fi
    source ./common.sh
else
    source $COMMON_SHELL
fi

PKG_SUFFIX=$(get_os_info | sed -n '1p')
OS_TYPE=$(get_os_info | sed -n '2p')
OS_VERSION_ID=$(get_os_info | tail -n 1)

# Check if the correct number of arguments is provided
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <compiler type> <version>"
    exit 1
fi

# check the compiler type, hcc or hgcc, first parameter
case $1 in
    "hcc")
        REMOTE_PATH=/hygon-devkit/4.0/2025-01-01/compiler/hcc/$2/hcc-$2.${PKG_SUFFIX}
        FILE_NAME=hcc-$2.${PKG_SUFFIX}
        LOCAL_DIR=$SCRIPT_DIR/hcc/pkg/$2
        ;;
    "hgcc")
        VERSION=$(echo $2 | cut -d'-' -f1)
        echo "VERSION: $VERSION"
        REMOTE_PATH=/hygon-devkit/4.0/2025-01-01/compiler/hgcc/$VERSION/
        LOCAL_DIR=$SCRIPT_DIR/hgcc/pkg/$VERSION
        if [ ! -f "$SFTP_TOOL" ]; then
            if [ ! -f ./sftp ]; then
                wget https://gitee.com/anolis/hygon-devkit/raw/master/tools/sftp
            fi
            chmod +x sftp
            FILE_NAME=$(./sftp list "$REMOTE_PATH" | grep -oP "hgcc-$2\.${PKG_SUFFIX}$")
        else
            FILE_NAME=$($SFTP_TOOL list "$REMOTE_PATH" | grep -oP "hgcc-$2\.${PKG_SUFFIX}$")
        fi
        if [ -z "$FILE_NAME" ]; then
            echo "File not found at sftp server"
            exit 1
        fi
        REMOTE_PATH=/hygon-devkit/4.0/2025-01-01/compiler/hgcc/$VERSION/$FILE_NAME
        LOCAL_DIR=$SCRIPT_DIR/hgcc/pkg/$VERSION
        ;;
    *)
        echo "Invalid compiler type, please use hcc or hgcc."
        exit 1
        ;;
esac


# Create the local directory if it doesn't exist
mkdir -p "$LOCAL_DIR"
echo "Downloading $REMOTE_PATH to $LOCAL_DIR/$FILE_NAME"

# If the directory don't have deb or rpm file, download it
if [ -z "$(ls -A "$LOCAL_DIR"/$FILE_NAME 2>/dev/null)" ] ; then
    if [ ! -f "$SFTP_TOOL" ]; then
        if [ ! -f ./sftp ]; then
            wget https://gitee.com/anolis/hygon-devkit/raw/master/tools/sftp
        fi
        chmod +x sftp
        ./sftp download "$REMOTE_PATH" $LOCAL_DIR/$FILE_NAME
    else
        $SFTP_TOOL download "$REMOTE_PATH" $LOCAL_DIR/$FILE_NAME
    fi
fi

# Detect the package type, use the dpkg -i or rpm -ivh command to install the package
if [ "$PKG_SUFFIX" == "deb" ]; then
    dpkg -i $LOCAL_DIR/$FILE_NAME
else
    rpm -ivh $LOCAL_DIR/$FILE_NAME
fi